package com.tengxing.e1.FactoryTest;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Criteria;

import android.location.GnssStatus;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.CellIdentity;
import android.telephony.CellInfo;
import android.telephony.CellInfoGsm;
import android.telephony.CellInfoLte;
import android.telephony.CellInfoWcdma;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Wireless_Test_Activity extends AppCompatActivity {
    private static final String TAG = "Wireless_Test_Activity";
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    Button btn_Wireless1, btn_Wireless2, btn_Wireless3, btn_Wireless4, btn_Wireless_Pass, btn_Wireless_Fail;
    TextView tV_Location_Scan_Res, tV_WiFi_Scan_Res, tV_BT_Scan_Res, tV_Mob_Scan_Res;
    private Location location;
    private LocationManager locationManager;
    private LocationListener locationListener;
    private GnssStatus.Callback gnssStatus_Callback;

    double latitude, longitude;
    private WifiManager wifiManager;
    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    ScanCallback bt_ScanCallback;
    BluetoothAdapter.LeScanCallback btLeScanCallback;

    BroadcastReceiver wifiScanReceiver, bluetoothScanReceiver;
    Map<String, String> bt_Scan_Map = new HashMap<>();
    Map<String, String> sat_Scan_Map = new HashMap<>();


    TelephonyManager telephonyManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_wireless_test);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        sharedPreferences = getSharedPreferences("Test_Result", MODE_PRIVATE);
        Factory_Wireless_InitView();
        Factory_Wireless_BTN();
        Init_Location();
        Scan_Sat_Init();
        Scan_WiFi_Init();
        Scan_BT_Init();
        Scan_Mob_Init();
    }

    private void Factory_Wireless_InitView() {
        tV_Location_Scan_Res = findViewById(R.id.tV_Location_Scan_Res);
        tV_WiFi_Scan_Res = findViewById(R.id.tV_WiFi_Scan_Res);
        tV_BT_Scan_Res = findViewById(R.id.tV_BT_Scan_Res);
        tV_Mob_Scan_Res = findViewById(R.id.tV_Mob_Scan_Res);
        //hideBottomUIMenu();
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }

    }
    private void Factory_Wireless_BTN() {
        btn_Wireless_Pass = findViewById(R.id.btn_Wireless_Pass);
        btn_Wireless_Pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editor = sharedPreferences.edit();
                editor = editor.putString("Wireless", "通过");
                if (editor.commit()) {
                    Toast.makeText(Wireless_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(Wireless_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(Wireless_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_Wireless_Fail = findViewById(R.id.btn_Wireless_Fail);
        btn_Wireless_Fail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editor = sharedPreferences.edit();
                editor = editor.putString("Wireless", "未通过");
                if (editor.commit()) {
                    Toast.makeText(Wireless_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(Wireless_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(Wireless_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_Wireless1 = findViewById(R.id.btn_Wireless1);
        btn_Wireless1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Scan_Location();
                //Scan_Sat();
            }
        });
        btn_Wireless2 = findViewById(R.id.btn_Wireless2);
        btn_Wireless2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Scan_WiFi();
            }
        });
        btn_Wireless3 = findViewById(R.id.btn_Wireless3);
        btn_Wireless3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //bluetoothAdapter.getBluetoothLeScanner().startScan(bt_ScanCallback);
                bt_Scan_Map.clear();
                bluetoothAdapter.startDiscovery();
            }
        });
        btn_Wireless4 = findViewById(R.id.btn_Wireless4);
        btn_Wireless4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Scan_Mob_Init();
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.S)
    private void Scan_BT_Init() {
        bt_ScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, android.bluetooth.le.ScanResult result) {
                super.onScanResult(callbackType, result);
            }

            @Override
            public void onBatchScanResults(List<android.bluetooth.le.ScanResult> results) {
                super.onBatchScanResults(results);
            }

            @Override
            public void onScanFailed(int errorCode) {
                super.onScanFailed(errorCode);
            }
        };


        btLeScanCallback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {

            }
        };

        bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH}, 1002);
            Toast.makeText(Wireless_Test_Activity.this, "需要蓝牙权限", Toast.LENGTH_SHORT).show();
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_SCAN}, 1002);
            Toast.makeText(Wireless_Test_Activity.this, "需要蓝牙扫描权限", Toast.LENGTH_SHORT).show();
        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_CONNECT}, 1002);
            //return;
        }
        if (!bluetoothAdapter.isEnabled()) {
// 启用蓝牙
            bluetoothAdapter.enable();
            return;
        }

        //
        bluetoothScanReceiver = new BroadcastReceiver() {


            @Override
            public void onReceive(Context context, Intent intent) {
                String bt_Scan_Res_Str = "";
                String action_str = intent.getAction();
                if (BluetoothDevice.ACTION_FOUND.equals(action_str)) {
                    BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    //Log.d(TAG, "Name:" + btDevice.getName() + " Addr:" + btDevice.getAddress());
                    bt_Scan_Map.put(btDevice.getName(), btDevice.getAddress());
                }
                //Enumeration<String> keys = bt_Scan_Dict.keys();
                Set<String> keys = bt_Scan_Map.keySet();
                for (String key : keys) {
                    bt_Scan_Res_Str = bt_Scan_Res_Str.concat("Name:" + key + " Addr:" + bt_Scan_Map.get(key) + "\n\n");
                }
                tV_BT_Scan_Res.setText(bt_Scan_Res_Str);
            }

        };
        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(bluetoothScanReceiver, intentFilter);
        bluetoothAdapter.startDiscovery();
        //bluetoothAdapter.getBluetoothLeScanner().startScan(bt_ScanCallback);
    }

    private void Scan_WiFi_Init() {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(Wireless_Test_Activity.this, "需要访问WLAN权限", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_WIFI_STATE}, 1001);
            //return;
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(Wireless_Test_Activity.this, "需要改变WLAN权限", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CHANGE_WIFI_STATE}, 1001);
            //return;
        }
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
            Toast.makeText(Wireless_Test_Activity.this, "WLAN未打开", Toast.LENGTH_SHORT).show();
            return;
        }
        wifiManager.startScan();
        wifiScanReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String wifi_Scan_Res_Str = "";
                List<ScanResult> scanResults = wifiManager.getScanResults();
                for (ScanResult scanResult : scanResults) {
                    //Log.d(TAG, "SSID:"+ scanResult.SSID + " RSSI:" + scanResult.level);
                    wifi_Scan_Res_Str = wifi_Scan_Res_Str.concat("SSID:" + scanResult.SSID + " BSSID:" + scanResult.BSSID + " RSSI:" + scanResult.level
                            + "dBn\n频率:" + scanResult.frequency + " 信道宽度:" + scanResult.channelWidth
                            + "\n\n");
                }
                tV_WiFi_Scan_Res.setText(wifi_Scan_Res_Str);
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        registerReceiver(wifiScanReceiver, intentFilter);
    }

    private void Scan_WiFi() {
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(Wireless_Test_Activity.this, "需要访问WLAN权限", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_WIFI_STATE}, 1001);
            //return;
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(Wireless_Test_Activity.this, "需要改变WLAN权限", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CHANGE_WIFI_STATE}, 1001);
            //return;
        }
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
            Toast.makeText(Wireless_Test_Activity.this, "WLAN未打开", Toast.LENGTH_SHORT).show();
            return;
        } else {
            wifiManager.startScan();
        }

    }

    private void Scan_Sat() {

    }

    private void Scan_Sat_Init() {
        gnssStatus_Callback = new GnssStatus.Callback() {
            @Override
            public void onStarted() {
                super.onStarted();
            }

            @Override
            public void onStopped() {
                super.onStopped();
            }

            @Override
            public void onFirstFix(int ttffMillis) {
                super.onFirstFix(ttffMillis);
            }

            @Override
            public void onSatelliteStatusChanged(@NonNull GnssStatus status) {
                String sat_Scan_Res_Str = "";
                sat_Scan_Map.clear();
                for (int i = 0; i < status.getSatelliteCount(); i++) {
                    Log.d(TAG, "i=" + i + ",getSvid=" + status.getSvid(i) + ",getConstellationType=" + status.getConstellationType(i));
                    sat_Scan_Res_Str = sat_Scan_Res_Str.concat(i + " - Svid:" + status.getSvid(i) +
                            " cn0:" + status.getCn0DbHz(i) +
                            " elevation:" + status.getElevationDegrees(i) +
                            " azimuth:" + status.getAzimuthDegrees(i) +
                            " usedInFix:" + status.usedInFix(i) + "\n\n"
                    );
                }
                tV_Location_Scan_Res.setText(sat_Scan_Res_Str);
                super.onSatelliteStatusChanged(status);
            }
        };
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(Wireless_Test_Activity.this, "搜星初始化：无定位权限", Toast.LENGTH_SHORT).show();
            return;
        }
        locationManager.registerGnssStatusCallback(gnssStatus_Callback);
    }


    private void Scan_Location() {
        try {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(Wireless_Test_Activity.this, "获取经纬度：无定位权限", Toast.LENGTH_SHORT).show();
                return;
            }
            //locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        } catch (Exception e) {
            Toast.makeText(Wireless_Test_Activity.this, "getLastKnownLocation:" + e, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "getLastKnownLocation:" + e);
        }
        try {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        } catch (Exception e) {
            Toast.makeText(Wireless_Test_Activity.this, "getLocation:" + e, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "getLocation:" + e);
        }
        String btn_str = "位置刷新\nlat:" + latitude + "\nlong:" + longitude;
        btn_Wireless1.setText(btn_str);
    }

    @SuppressLint("ServiceCast")
    private void Init_Location() {

        String provider = LocationManager.GPS_PROVIDER;
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        /*try{
            List<String> providerList = locationManager.getProviders(true);
            if (providerList.contains(LocationManager.GPS_PROVIDER)){
                provider = LocationManager.GPS_PROVIDER;
            } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)){
                provider = LocationManager.NETWORK_PROVIDER;
            } else {
                // 当没有可用的位置提供器时，弹出Toash提示用户
                Toast.makeText(this, "No Location provider to use", Toast.LENGTH_SHORT).show();
                Log.e(TAG,"getSystemService:No Location provider to use");
                return;
            }
        }catch (Exception e){
            Toast.makeText(Wireless_Test_Activity.this, "getSystemService:"+e, Toast.LENGTH_SHORT).show();
            Log.e(TAG,"getSystemService:"+e);
            provider = LocationManager.GPS_PROVIDER;
        }*/

        try {
            location = locationManager.getLastKnownLocation(provider);
        } catch (Exception e) {
            Toast.makeText(Wireless_Test_Activity.this, "getLastKnownLocation:" + e, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "getLastKnownLocation:" + e);
        }

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(@NonNull Location location) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                String btn_str = "位置刷新\nlat:" + latitude + "\nlong:" + longitude;
                btn_Wireless1.setText(btn_str);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(@NonNull String provider) {
            }

            @Override
            public void onProviderDisabled(@NonNull String provider) {
            }

        };
        locationManager.requestLocationUpdates(provider, 2000, 8, locationListener);
    }

    private void Scan_Mob_Init() {
        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(Wireless_Test_Activity.this, "基站扫描：需要定位权限", Toast.LENGTH_SHORT).show();
            return;
        }
        List<CellInfo> cellInfos = telephonyManager.getAllCellInfo();
        List<String> cellInfoList = new ArrayList<>();
        String scan_Mob_Res_Str = "";
        if(cellInfos != null){
            for(CellInfo cellInfo : cellInfos){
                if (cellInfo instanceof CellInfoGsm) {
                    CellInfoGsm cellInfoGsm = (CellInfoGsm) cellInfo;
                    cellInfoList.add("GSM Cell: " + cellInfoGsm.getCellIdentity().toString() + " Sign:" + cellInfoGsm.getCellSignalStrength());
                    scan_Mob_Res_Str = scan_Mob_Res_Str.concat("GSM Cell: " + cellInfoGsm.getCellIdentity().toString() + " Sign:" + cellInfoGsm.getCellSignalStrength() + "\n\n");
                } else if (cellInfo instanceof CellInfoWcdma) {
                    CellInfoWcdma cellInfoWcdma = (CellInfoWcdma) cellInfo;
                    cellInfoList.add("WCDMA Cell: " + cellInfoWcdma.getCellIdentity().toString() + " Sign:" + cellInfoWcdma.getCellSignalStrength());
                    scan_Mob_Res_Str = scan_Mob_Res_Str.concat("WCDMA Cell: " + cellInfoWcdma.getCellIdentity().toString() + " Sign:" + cellInfoWcdma.getCellSignalStrength() + "\n\n");
                } else if (cellInfo instanceof CellInfoLte) {
                    CellInfoLte cellInfoLte = (CellInfoLte) cellInfo;
                    cellInfoList.add("LTE Cell: " + cellInfoLte.getCellIdentity().toString() + " Sign:" + cellInfoLte.getCellSignalStrength());
                    scan_Mob_Res_Str = scan_Mob_Res_Str.concat("LTE Cell: " + cellInfoLte.getCellIdentity().toString() + " Sign:" + cellInfoLte.getCellSignalStrength() + "\n\n");
                }
            }
            tV_Mob_Scan_Res.setText(scan_Mob_Res_Str);
        }

    }

    @Override
    public void onBackPressed() {
        if (locationManager != null) {
            locationManager.removeUpdates(locationListener);
            locationManager.unregisterGnssStatusCallback(gnssStatus_Callback);
        }
        try {
            unregisterReceiver(wifiScanReceiver);
        }catch (Exception e){

        }
        try {
            unregisterReceiver(bluetoothScanReceiver);
        }catch (Exception e){

        }
        Intent intent = new Intent(Wireless_Test_Activity.this, MainActivity.class);
        startActivity(intent);
        finish();
        Toast.makeText(Wireless_Test_Activity.this, "直接退出不会保存结果", Toast.LENGTH_SHORT).show();
        super.onBackPressed();
    }

}